package vn.hanelsoft.openwifi.control;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.hanelsoft.openwifi.R;
import vn.hanelsoft.openwifi.common.ConstCommon;
import vn.hanelsoft.openwifi.common.UtilsCommon;
import vn.hanelsoft.openwifi.model.adapter.AdapterSpinner;
import vn.hanelsoft.openwifi.model.delegate.ServerDelegate;
import vn.hanelsoft.openwifi.model.object.ObjectFacebook;
import vn.hanelsoft.openwifi.model.object.ObjectWifi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.StaticLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.maps.model.LatLng;

public class OpenWifiActivity extends Activity implements OnClickListener {

	Context mContext;
	Dialog dialog;

	EditText edPasswordKey, edEmail;
	ImageView imgGoogleMap;
	Button btnUpdate;
	Spinner spinnerSSID;
	AdapterSpinner adapterSpinner;
	ArrayList<ObjectWifi> listWifiObject;
	ObjectWifi mObjectWifi;
	ObjectFacebook mObjectFacebook;
	boolean checkDisconnectWifi = true;
	private AdView mAdView;

	// Current Location
	private LocationManager locManager;
	private LocationListener locListener;
	private Location currentLocation;
	private boolean gps_enabled = false;
	private boolean network_enabled = false;

	private TextView mTextDown;
	private TextView mTextLat;
	private TextView mTextLong;
	private TextView mTextTotalTime;

	ArrayList<ObjectWifi> listWifiOnServer;

	boolean isClickAds;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_open_wifi);
		addViewAds();
		initDB();
		initView();

		mThread.start();

		mTextDown.setTypeface(UtilsCommon.getFontCustom(this));
	}

	Thread mThread = new Thread(new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setTextDown();
					}
				});
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	});

	void setTextDown() {
		String strMinuter = "";
		String strSecond = "";
		String strTime = "";
		if (ConstCommon.isServiceRunning) {
			if (ConstCommon.minuterService > 9)
				strMinuter += ConstCommon.minuterService;
			else
				strMinuter += "0" + ConstCommon.minuterService;
			if (ConstCommon.secondService > 9)
				strSecond += ConstCommon.secondService;
			else
				strSecond += "0" + ConstCommon.secondService;
			strTime = strMinuter + ":" + strSecond;
		}

		mTextDown.setText(strTime);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnUpdate:
			checkDisconnectWifi = false;
			if (edPasswordKey.getText().toString().equals("")) {
				Toast.makeText(mContext,
						mContext.getString(R.string.password_wifi_not_null),
						Toast.LENGTH_LONG).show();
			} else {
				String strEmail = edEmail.getText().toString();
				if (strEmail.length() > 0) {
					if (UtilsCommon.isValidEmail(strEmail)) {
						updateWifi(mhandler);
					} else {
						Toast.makeText(mContext,
								mContext.getString(R.string.email_invalid),
								Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(mContext,
							mContext.getString(R.string.email_not_null),
							Toast.LENGTH_LONG).show();
				}
			}
			break;
		case R.id.imgGoogleMap:
			checkDisconnectWifi = false;
			Intent intent = new Intent(mContext, MapWifiActivity.class);
			startActivity(intent);
			overridePendingTransition(
					R.drawable.activity_transaction_trans_left_in,
					R.drawable.activity_transaction_trans_left_out);

			break;

		default:
			break;
		}

	}

	@Override
	protected void onStop() {
		if (checkDisconnectWifi == false) {
			checkDisconnectWifi = true;
		} else if (isClickAds) {
			isClickAds = false;
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst) {
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				} else
					ConstCommon.totalSecondService = (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterWait;
				ConstCommon.secondService = 0;
				ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE), String
						.valueOf(ConstCommon.totalSecondService));
			}
		} else {
			//
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst) {
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				} else
					ConstCommon.totalSecondService += (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterFirst;
				ConstCommon.secondService = 0;
			}
			ServerDelegate.updateTotalTimeShowAd(mhandler1, UtilsCommon
					.getStringSetting(getBaseContext(),
							ConstCommon.KEY_WIFI_STORE), String
					.valueOf(ConstCommon.totalSecondService));
			ConstCommon.totalSecondService = 0;
			ConstCommon.isServiceRunning = false;
			UtilsCommon.setStringSetting(getBaseContext(),
					ConstCommon.KEY_WIFI_STORE, "");
			Log.i("Service1", "Kill");
		}
		super.onStop();
		// if (checkDisconnectWifi == false) {
		// checkDisconnectWifi = true;
		// } else {
		// UtilsCommon.disConnectWifi(this);
		// }
		// super.onStop();
	}

	Handler mhandler1 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				UtilsCommon.killApp(getApplicationContext());
			}
		}
	};

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		checkDisconnectWifi = false;
		activityFinish();
	}

	@Override
	protected void onPause() {
		mAdView.pause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mAdView.resume();
	}

	@Override
	protected void onDestroy() {
		mAdView.destroy();
		super.onDestroy();
	}

	/*------------------- Custom Function ------------------------*/

	void addViewAds() {
		mAdView = (AdView) findViewById(R.id.adView);
		mAdView.loadAd(new AdRequest.Builder().build());
		mAdView.setAdListener(new AdListener() {

			@Override
			public void onAdOpened() {
				super.onAdOpened();
				isClickAds = true;
				ServerDelegate.updateTotalTimeClickAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE));
				// checkDisconnectWifi = false;
				// if(ConstCommon.isServiceRunning){
				// if(ConstCommon.totalSecondService == 0)
				// ConstCommon.totalSecondService = (ConstCommon.minuterFirst*60
				// - (ConstCommon.minuterService*60+ConstCommon.secondService));
				// else
				// ConstCommon.totalSecondService = (ConstCommon.minuterWait*60
				// - (ConstCommon.minuterService*60+ConstCommon.secondService));
				// ConstCommon.minuterService = ConstCommon.minuterWait;
				// ConstCommon.secondService = 0;
				// ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
				// .getStringSetting(getBaseContext(),
				// ConstCommon.KEY_WIFI_STORE), String
				// .valueOf(ConstCommon.totalSecondService));
				// }
			}

			@Override
			public void onAdLoaded() {
				super.onAdLoaded();
			}

		});
	}

	void initDB() {
		checkDisconnectWifi = true;
		mContext = this;
		listWifiObject = new ArrayList<ObjectWifi>();
		listWifiOnServer = new ArrayList<ObjectWifi>();
		getCurrentLocation(mContext);

		Intent intent = getIntent();
		if (intent != null) {
			try {
				mObjectFacebook = (ObjectFacebook) intent.getExtras()
						.getSerializable(ConstCommon.KEY_FACEBOOK);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	void loadWifiFromServer() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (currentLocation == null) {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (currentLocation != null) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								ServerDelegate.getWifi(getWifiHandler,
										String.valueOf(currentLocation
												.getLatitude()), String
												.valueOf(currentLocation
														.getLongitude()));
							}
						});
					}

				}
			}
		}).start();
	}

	void setViewSpinner() {
		listWifiObject = UtilsCommon.getAllListWifiObject(mContext);
		adapterSpinner = new AdapterSpinner(mContext, listWifiObject);
		spinnerSSID.setAdapter(adapterSpinner);
	}

	void updateListWifi() {
		for (int i = 0; i < listWifiObject.size(); i++) {
			ObjectWifi objWifi = listWifiObject.get(i);
			objWifi.setLat(String.valueOf(currentLocation.getLatitude()));
			objWifi.setLng(String.valueOf(currentLocation.getLongitude()));
			for (int j = 0; j < listWifiOnServer.size(); j++) {
				ObjectWifi objWifiServer = listWifiOnServer.get(j);
				if (objWifi.getWifiBSSID().equals(objWifiServer.getWifiBSSID())) {
					objWifi.setEmail(objWifiServer.getEmail());
					objWifi.setWifiPassword(objWifiServer.getWifiPassword());
					objWifi.setLat(objWifiServer.getLat());
					objWifi.setLng(objWifiServer.getLng());
					objWifi.setTotalTime(objWifiServer.getTotalTime());
				}
			}
		}
		listWifiOnServer.clear();
		adapterSpinner.notifyDataSetChanged();
		if(mTextLat.getText().equals("")){
			mTextLat.setText(String.valueOf(currentLocation.getLatitude()));
		}
		if(mTextLong.getText().equals("")){
			mTextLong.setText(String.valueOf(currentLocation.getLongitude()));
		}
	}
	
	void initView() {
		spinnerSSID = (Spinner) findViewById(R.id.spinnerSSID);
		spinnerSSID.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				final ObjectWifi obj = listWifiObject.get(position);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						edPasswordKey.setText(obj.getWifiPassword());
						edEmail.setText(obj.getEmail());
						mTextLat.setText(obj.getLat());
						mTextLong.setText(obj.getLng());
						mTextTotalTime.setText(obj.getTotalTime());
					}
				});
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		edPasswordKey = (EditText) findViewById(R.id.edPasswordKey);
		edPasswordKey.setTypeface(UtilsCommon.getFontCustom(mContext));
		edEmail = (EditText) findViewById(R.id.edEmail);
		edEmail.setTypeface(UtilsCommon.getFontCustom(mContext));
		btnUpdate = (Button) findViewById(R.id.btnUpdate);
		btnUpdate.setTypeface(UtilsCommon.getFontCustom(mContext));
		btnUpdate.setOnClickListener(this);
		imgGoogleMap = (ImageView) findViewById(R.id.imgGoogleMap);
		imgGoogleMap.setOnClickListener(this);

		mTextDown = (TextView) findViewById(R.id.chrome_text_time_down);
		mTextLat = (TextView) findViewById(R.id.lat);
		mTextLong = (TextView) findViewById(R.id.lng);
		mTextTotalTime = (TextView) findViewById(R.id.edTotalTime);

		setViewSpinner();
		loadWifiFromServer();
	}

	void activityFinish() {
		finish();
		overridePendingTransition(
				R.drawable.activity_transaction_trans_right_in,
				R.drawable.activity_transaction_trans_right_out);
	}

	void updateWifi(Handler mhandler) {
		if (dialog == null || dialog.isShowing() == false) {
			dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_loading);
			dialog.show();
		}

		mObjectWifi = new ObjectWifi();
		mObjectWifi = (ObjectWifi) spinnerSSID.getSelectedItem();
		mObjectWifi.setEmail(edEmail.getText().toString());
		mObjectWifi.setFacebookId(mObjectFacebook.getFacebookId());
		mObjectWifi.setFacebookName(mObjectFacebook.getName());
		mObjectWifi.setFacebookImg(mObjectFacebook.getSrcImage());
		if (currentLocation != null) {
			mObjectWifi.setLat(String.valueOf(currentLocation.getLatitude()));
			mObjectWifi.setLng(String.valueOf(currentLocation.getLongitude()));
		} else {
			boolean isGetLocation = false;
			while (isGetLocation == false) {
				if (currentLocation != null) {
					mObjectWifi.setLat(String.valueOf(currentLocation
							.getLatitude()));
					mObjectWifi.setLng(String.valueOf(currentLocation
							.getLongitude()));
					// Log.d("Luong",
					// "2----------------------- Lat: "+mObjectWifi.getLat());
					// Log.d("Luong",
					// "2----------------- Lng: "+mObjectWifi.getLng());
					isGetLocation = true;
				} else {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		mObjectWifi.setWifiPassword(edPasswordKey.getText().toString());
		ServerDelegate.setWifi(mhandler, mObjectWifi);
	}

	Handler getWifiHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			listWifiOnServer.clear();
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					JSONArray data = new JSONArray();
					data = dataJSONObject.getJSONArray("data");
					if (data != null && data.length() > 0) {
						JSONObject wifiJSONObject = null;
						for (int i = 0; i < data.length(); i++) {
							wifiJSONObject = new JSONObject();
							wifiJSONObject = data.getJSONObject(i);

							mObjectWifi = new ObjectWifi();
							mObjectWifi.setWifiBSSID(wifiJSONObject
									.getString("BSSID"));
							mObjectWifi.setWifiSSID(wifiJSONObject
									.getString("SSID"));
							mObjectWifi.setWifiPassword(wifiJSONObject
									.getString("passkey"));
							mObjectWifi.setEmail(wifiJSONObject
									.getString("email"));
							mObjectWifi.setLat(wifiJSONObject
									.getString("lattitue"));
							mObjectWifi.setLng(wifiJSONObject
									.getString("longitue"));
							mObjectWifi.setTotalTime(wifiJSONObject
									.getString("adshowtotaltime"));
							listWifiOnServer.add(mObjectWifi);
						}
						wifiJSONObject = null;
						// vf.setDisplayedChild(1);
					}
				} catch (Exception e) {
					// vf.setDisplayedChild(2);
				}
			} else {
				// vf.setDisplayedChild(2);
			}
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					updateListWifi();
				}
			});
		}
	};

	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					String status = dataJSONObject.getString("data");
					if (status.equals("1")) {
						// Success
						Toast.makeText(mContext,
								mContext.getString(R.string.insert_success),
								Toast.LENGTH_LONG).show();
					} else if (status.equals("0")) {
						// failt
						Toast.makeText(mContext,
								mContext.getString(R.string.update_failt),
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(mContext,
								mContext.getString(R.string.update_success),
								Toast.LENGTH_LONG).show();
					}

					if (dialog.isShowing()) {
						dialog.dismiss();
					}

				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	};

	// lay vi tri hien tai
	private void getCurrentLocation(final Context context) {
		threadGetCurrentLocation.start();
	}

	// Luong
	Thread threadGetCurrentLocation = new Thread(new Runnable() {

		@Override
		public void run() {
			Looper.prepare();
			long minTime = 500;// Khai bao thoi gian toi thieu de check lai
								// mylocation la 1/2s
			float minDistance = 1;// khai bao khoang cach thay doi toi thieu la
									// 50 m de check lai mylocation
			// load class lay vi tri hien tai
			locManager = (LocationManager) mContext
					.getSystemService(Context.LOCATION_SERVICE);
			// thuc hien check gps va lay vi tri hien tai
			locListener = new MyLocationListener();
			gps_enabled = locManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);
			network_enabled = locManager
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
			if (network_enabled) {
				locManager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, minTime, minDistance,
						locListener);
			} else if (gps_enabled) {
				locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
						minTime, minDistance, locListener);
			}

			// thuc hien lap nhieu lan
			Looper.loop();
		}
	});

	class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			if (location != null) {
				currentLocation = location;
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}
	}
}
